<?php
/**
 * This file is part of webman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace process;

use Workerman\Connection\TcpConnection;
use Workerman\Lib\Timer;

class Websocket
{
    protected $HEARTBEAT_TIME = 55;
    public function onConnect(TcpConnection $connection)
    {
        //-------------------------------------------心跳检测---------------------------------
        Timer::add(1, function () use ($connection) {
            $time_now = time();
            // 有可能该connection还没收到过消息，则lastMessageTime设置为当前时间
            if (empty($connection->lastMessageTime)) {
                $connection->lastMessageTime = $time_now;
            }else{
                // 上次通讯时间间隔大于心跳间隔，则认为客户端已经下线，关闭连接
                if ($time_now - ($connection->lastMessageTime) > ($this->HEARTBEAT_TIME)) {
                    $connection->close();
                } else {
                    $connection->send('{"type":"ping"}');
                }
            }
        });
        echo "onConnect\n";
    }

    public function onWebSocketConnect(TcpConnection $connection, $http_buffer)
    {
        echo "onWebSocketConnect\n";
    }

    public function onMessage(TcpConnection $connection, $data)
    {
        $connection->send($data);
    }

    public function onClose(TcpConnection $connection)
    {
        echo "onClose\n";
    }

}
